package service;

import common.Message;
import common.MessageType;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class ServiceConnectClientThread extends Thread{
    Socket socket;
    String userId;


    public ServiceConnectClientThread(Socket socket,String userId)
    {
        this.socket = socket;
        this.userId = userId;
    }

    @Override
    public void run() {
        try {
            while (true)
            {
                //得不到数据就会阻塞
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                Message message = (Message)objectInputStream.readObject();

                if (message.getMesType().equals(MessageType.MESSAGE_GET_ONLINE_FRIEND))
                {
                    System.out.println("用户:"+message.getSender()+"获取用户在线列表");
                    //读取在线列表
                    StringBuffer stringBuffer = new StringBuffer();
                    HashMap<String, ServiceConnectClientThread> onlineUsers = ManageServiceConnectClientThread.stringServiceConnectClientThreadHashMap;
                    Set<String> strings = onlineUsers.keySet();
                    for (String string : strings) {
                        stringBuffer.append(" "+string);
                    }
                    //写入message
                    Message returnMessage = new Message();
                    returnMessage.setMesType(MessageType.MESSAGE_RET_ONLINE_FRIEND);
                    returnMessage.setContent(stringBuffer.toString());
                    returnMessage.setGetter(message.getSender());
                    //返回
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(returnMessage);
                }
                //客户端退出
                else if (message.getMesType().equals(MessageType.MESSAGE_CLIENT_EXIT))
                {
                    System.out.println("用户："+userId+"退出链接");
                    //关闭链接
                    socket.close();
                    //线程集合删除
                    ManageServiceConnectClientThread.removeThreadMap(message.getSender());
                    //终止线程
                    break;
                }
                //转发消息
                else if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES) && judgeOrSaveMessage(message))
                {
                    //没有接收人代表群发
                    if (message.getGetter() != null) {
                        //根据消息中的geter找到是谁要收消息
                        ServiceConnectClientThread threadMap = ManageServiceConnectClientThread.getThreadMap(message.getGetter());
                        Socket socket = threadMap.getSocket();
                        //发送给对应的socket
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                        objectOutputStream.writeObject(message);
                    }
                    else {
                        //群发
                        HashMap<String, ServiceConnectClientThread> socketMaps = ManageServiceConnectClientThread.stringServiceConnectClientThreadHashMap;
                        //遍历在线用户发送（除了自己）
                        Set<String> strings = socketMaps.keySet();
                        for (String string : strings) {
                            if (!string.equals(message.getSender())) {
                                Socket socket = socketMaps.get(string).getSocket();
                                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                                objectOutputStream.writeObject(message);
                            }
                        }
                    }
                }
                //转发文件
                else if (message.getMesType().equals(MessageType.MESSAGE_FILE) && judgeOrSaveMessage(message))
                {
                    //根据消息中的geter找到是谁要收消息
                    ServiceConnectClientThread threadMap = ManageServiceConnectClientThread.getThreadMap(message.getGetter());
                    Socket socket = threadMap.getSocket();
                    //发送给对应的socket
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(message);
                }
                else {
                    System.out.println("暂时没处理");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    //判断用户是否在线，在线正常发送，不在线缓存消息，等用户登录后读取
    private boolean judgeOrSaveMessage(Message message)
    {
        //获得接收者
        String getter = message.getGetter();
        boolean hasExist = ManageServiceConnectClientThread.stringServiceConnectClientThreadHashMap.containsKey(getter);
        //不存在保存数据
        if (!hasExist)
        {
            MangeMessage.addMessage(getter,message);
            return false;
        }
        return true;
    }
}
